package com.xyz.yygh.cmn.controller;

import com.xyz.yygh.cmn.service.DictService;
import com.xyz.yygh.common.result.Result;
import com.xyz.yygh.model.cmn.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "数据字段接口")
@RestController
@RequestMapping("/admin/cmn/dict")
public class DictController {

    @Autowired
    private DictService dictService;

    @ApiOperation(value = "根据id查找子集")
    @GetMapping("findChildData/{parentId}")
    public Result findChildData(@PathVariable Long parentId){
        List<Dict> list = dictService.findChildData(parentId);
        return Result.ok(list);
    }

    @ApiOperation("导出数据字典")
    @GetMapping("/exportData")
    public void exportData(HttpServletResponse httpServletResponse){
        dictService.exportData(httpServletResponse);
    }

    @ApiOperation("上传数据字典")
    @PostMapping("importData")
    public Result importData(MultipartFile file){
        dictService.importDictData(file);
        return Result.ok();
    }

    @ApiOperation(value = "新增节点")
    @PostMapping("")
    @CacheEvict(value = "dict",allEntries = true)
    public Result create (@RequestBody Dict dict){
        dict.setIsDeleted(0);
        boolean flag = dictService.save(dict);
        if(flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @ApiOperation(value = "修改节点")
    @PutMapping("")
    @CacheEvict(value = "dict",allEntries = true)
    public Result update (@RequestBody Dict dict){
        dict.setIsDeleted(0);
        boolean flag = dictService.updateById(dict);
        if(flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
}
